package com.justgame.project.base.filter;

import com.google.gson.Gson;
import com.justgame.project.cloud.common.constant.Auth2Token;
import com.justgame.project.cloud.common.constant.Const;
import com.justgame.project.cloud.common.constant.Result;
import com.justgame.project.cloud.common.util.HttpContextUtil;
import com.justgame.project.cloud.common.util.TokenUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 身份过滤器
 */
public class Auth2Filter extends AuthenticatingFilter {

    @Override
    protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) {
        return new Auth2Token(TokenUtil.getToken((HttpServletRequest) request));
    }


    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        return ((HttpServletRequest) request).getMethod().equals(RequestMethod.OPTIONS.name());
    }


    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        String token = TokenUtil.getToken((HttpServletRequest) request);
        if (StringUtils.isBlank(token)) {
            HttpServletResponse httpResponse = (HttpServletResponse) response;
            httpResponse.setContentType("application/json;charset=utf-8");
            httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
            httpResponse.setHeader("Access-Control-Allow-Origin", HttpContextUtil.getOrigin());
            String Json = new Gson().toJson(Result.fail(Const.CODE_TOKEN_INVALID_CHINESE, Const.CODE_TOKEN_INVALID));
            httpResponse.getWriter().print(Json);
            return false;
        }
        return executeLogin(request, response);
    }


    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e,
                                     ServletRequest request, ServletResponse response) {
        HttpServletResponse res = (HttpServletResponse) response;
        res.setContentType("application/json;charset=utf-8");
        res.setHeader("Access-Control-Allow-Credentials", "true");
        res.setHeader("Access-Control-Allow-Origin", HttpContextUtil.getOrigin());
        try {
            Throwable throwable = e.getCause() == null ? e : e.getCause();
            String Json = new Gson().toJson(Result.fail(throwable.getMessage(), Const.CODE_TOKEN_INVALID));
            res.getWriter().print(Json);
        } catch (IOException ex) {
            // ...
        }
        return false;
    }

}
